"""
MAESS 生命周期管理器
负责管理系统服务的启动、关闭和健康检查
"""

import asyncio
import time
from typing import Dict, Any, Optional
from datetime import datetime
from dataclasses import dataclass

from utils.logger import logger
from app.core.config import settings      # 引入配置
# performance_dashboard_service 延迟导入，避免循环依赖


@dataclass
class ServiceHealth:
    """服务健康状态"""
    status: str
    message: str
    timestamp: str
    details: Optional[Dict[str, Any]] = None


class LifespanManager:
    """生命周期管理器"""
    
    def __init__(self):
        self.start_time = time.time()
        self.background_tasks = []
        self.services = {}
        self.performance_dashboard = None
        
    async def start_background_tasks(self):
        """启动后台任务"""
        try:
            logger.info("启动生命周期管理器后台任务...")
            
            # 初始化性能监控仪表板
            if hasattr(settings, 'performance_dashboard') and settings.performance_dashboard.enabled:
                from app.services.performance_dashboard_service import PerformanceDashboardService
                self.performance_dashboard = PerformanceDashboardService()
                await self.performance_dashboard.initialize()
                logger.info("性能监控仪表板服务已启动")
            
            logger.info("生命周期管理器后台任务启动完成")
            
        except Exception as e:
            logger.error(f"启动后台任务失败: {str(e)}")
            raise
    
    async def stop_background_tasks(self):
        """停止后台任务"""
        try:
            logger.info("停止生命周期管理器后台任务...")
            
            # 关闭性能监控仪表板
            if self.performance_dashboard:
                await self.performance_dashboard.close()
                self.performance_dashboard = None
                logger.info("性能监控仪表板服务已关闭")
            
            # 取消所有后台任务
            for task in self.background_tasks:
                if not task.done():
                    task.cancel()
                    
            # 等待所有任务完成
            if self.background_tasks:
                await asyncio.gather(*self.background_tasks, return_exceptions=True)
                
            logger.info("生命周期管理器后台任务停止完成")
            
        except Exception as e:
            logger.error(f"停止后台任务失败: {str(e)}")
            raise
    
    async def check_database_health(self) -> Dict[str, Any]:
        """检查数据库健康状态"""
        try:
            # 这里应该调用实际的数据库健康检查逻辑
            # 暂时返回模拟数据
            return {
                "status": "healthy",
                "message": "数据库连接正常",
                "timestamp": datetime.now().isoformat(),
                "details": {
                    "connection_pool_size": 10,
                    "active_connections": 3,
                    "database_version": "PostgreSQL 14.5"
                }
            }
        except Exception as e:
            return {
                "status": "unhealthy",
                "message": f"数据库健康检查失败: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }
    
    async def check_redis_health(self) -> Dict[str, Any]:
        """检查Redis健康状态"""
        try:
            # 这里应该调用实际的Redis健康检查逻辑
            # 暂时返回模拟数据
            return {
                "status": "healthy",
                "message": "Redis连接正常",
                "timestamp": datetime.now().isoformat(),
                "details": {
                    "connected_clients": 15,
                    "used_memory_human": "125.5M",
                    "redis_version": "6.2.6"
                }
            }
        except Exception as e:
            return {
                "status": "unhealthy",
                "message": f"Redis健康检查失败: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }
    
    async def check_workflow_engine_health(self) -> Dict[str, Any]:
        """检查工作流引擎健康状态"""
        try:
            # 这里应该调用实际的工作流引擎健康检查逻辑
            # 暂时返回模拟数据
            return {
                "status": "healthy",
                "message": "工作流引擎运行正常",
                "timestamp": datetime.now().isoformat(),
                "details": {
                    "active_workflows": 5,
                    "completed_workflows": 1250,
                    "failed_workflows": 3
                }
            }
        except Exception as e:
            return {
                "status": "unhealthy",
                "message": f"工作流引擎健康检查失败: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }
    
    async def check_task_scheduler_health(self) -> Dict[str, Any]:
        """检查任务调度器健康状态"""
        try:
            # 这里应该调用实际的任务调度器健康检查逻辑
            # 暂时返回模拟数据
            return {
                "status": "healthy",
                "message": "任务调度器运行正常",
                "timestamp": datetime.now().isoformat(),
                "details": {
                    "queued_tasks": 12,
                    "running_tasks": 8,
                    "completed_tasks": 3456
                }
            }
        except Exception as e:
            return {
                "status": "unhealthy",
                "message": f"任务调度器健康检查失败: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }
    
    async def check_performance_dashboard_health(self) -> Dict[str, Any]:
        """检查性能监控仪表板健康状态"""
        try:
            # 导入性能监控仪表板服务
            from app.services.performance_dashboard_service import get_performance_dashboard_service
            
            # 获取服务实例
            dashboard_service = await get_performance_dashboard_service()
            
            if not dashboard_service or not hasattr(dashboard_service, 'is_initialized'):
                return {
                    "status": "disabled",
                    "message": "性能监控仪表板服务未初始化",
                    "timestamp": datetime.now().isoformat()
                }
            
            # 检查性能监控仪表板服务状态
            is_healthy = await dashboard_service.health_check()
            
            if is_healthy:
                return {
                    "status": "healthy",
                    "message": "性能监控仪表板运行正常",
                    "timestamp": datetime.now().isoformat(),
                    "details": {
                        "service_enabled": True,
                        "metrics_collected": dashboard_service.get_metrics_count(),
                        "alerts_active": dashboard_service.get_active_alerts_count()
                    }
                }
            else:
                return {
                    "status": "unhealthy",
                    "message": "性能监控仪表板运行异常",
                    "timestamp": datetime.now().isoformat(),
                    "details": {
                        "service_enabled": True,
                        "error": "服务内部错误"
                    }
                }
                
        except Exception as e:
            return {
                "status": "unhealthy",
                "message": f"性能监控仪表板健康检查失败: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }
    
    async def get_readiness_checks(self) -> Dict[str, Any]:
        """获取就绪检查"""
        try:
            # 执行所有健康检查
            health_checks = await asyncio.gather(
                self.check_database_health(),
                self.check_redis_health(),
                self.check_workflow_engine_health(),
                self.check_task_scheduler_health(),
                self.check_performance_dashboard_health(),
                return_exceptions=True
            )
            
            checks = {
                "database": health_checks[0] if not isinstance(health_checks[0], Exception) else {
                    "status": "error",
                    "message": str(health_checks[0]),
                    "timestamp": datetime.now().isoformat()
                },
                "redis": health_checks[1] if not isinstance(health_checks[1], Exception) else {
                    "status": "error",
                    "message": str(health_checks[1]),
                    "timestamp": datetime.now().isoformat()
                },
                "workflow_engine": health_checks[2] if not isinstance(health_checks[2], Exception) else {
                    "status": "error",
                    "message": str(health_checks[2]),
                    "timestamp": datetime.now().isoformat()
                },
                "task_scheduler": health_checks[3] if not isinstance(health_checks[3], Exception) else {
                    "status": "error",
                    "message": str(health_checks[3]),
                    "timestamp": datetime.now().isoformat()
                },
                "performance_dashboard": health_checks[4] if not isinstance(health_checks[4], Exception) else {
                    "status": "error",
                    "message": str(health_checks[4]),
                    "timestamp": datetime.now().isoformat()
                }
            }
            
            # 计算整体状态
            all_healthy = all(
                check.get("status") == "healthy" or check.get("status") == "disabled" 
                for check in checks.values()
            )
            
            return {
                "status": "ready" if all_healthy else "not_ready",
                "checks": checks,
                "timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            return {
                "status": "error",
                "message": f"就绪检查失败: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }
    
    async def get_uptime(self) -> Dict[str, Any]:
        """获取系统运行时间"""
        uptime_seconds = time.time() - self.start_time
        return {
            "uptime_seconds": uptime_seconds,
            "uptime_human": self._format_uptime(uptime_seconds),
            "start_time": datetime.fromtimestamp(self.start_time).isoformat(),
            "current_time": datetime.now().isoformat()
        }
    
    def _format_uptime(self, seconds: float) -> str:
        """格式化运行时间"""
        days = int(seconds // 86400)
        hours = int((seconds % 86400) // 3600)
        minutes = int((seconds % 3600) // 60)
        
        parts = []
        if days > 0:
            parts.append(f"{days}天")
        if hours > 0:
            parts.append(f"{hours}小时")
        if minutes > 0:
            parts.append(f"{minutes}分钟")
        
        return " ".join(parts) if parts else "少于1分钟"


# 创建全局生命周期管理器实例
lifespan_manager = LifespanManager()

# 导入设置（解决循环导入问题）
try:
    from config.settings import settings
except ImportError:
    settings = None